package workexp.alg.question.linklist;

import org.junit.Test;
import workexp.alg.env.ListNode;

public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode result,pre,left,right;
        pre= new ListNode();
        pre.next=head;
        left=head;
        right=head;
        for (int i = 0; i < n-1; i++) {
            right=right.next;
        }
        while (right.next!=null){
            right=right.next;
            left=left.next;
            pre=pre.next;
        }
        if(left==head){
            result=left.next;
        }else{
            pre.next=left.next;
            result=head;
        }

        return result;
    }

    @Test
    public void test(){
        ListNode head = ListNode.genList(new int[]{1,2,3,4,5});
        ListNode res = removeNthFromEnd(head,2);
        res.printLinkList();

    }
}
